axios.defaults.baseURL = 'https://api.github.com/users/';

let preset_themes = [
  {
    value: "primary",
    text: "主题",
  },
  {
    value: "error",
    text: "错误",
  },
  {
    value: "success",
    text: "成功",
  },
  {
    value: "default",
    text: "默认",
  },
]


function createNotice(node,tips_text,type){
  let notice_list = document.querySelectorAll('.notice')
  let notice = document.createElement('div')
  notice.classList.add('notice')

  // 通知盒子的高度
  let notice_height = 50
  // 通知盒子的bottom默认值
  let default_bottom = 10
  // 每个通知盒子的间距
  let box_spacing = 10
  if (notice_list.length) {
    notice.style.transform = `translate(-50%,${((notice_height + box_spacing) * notice_list.length + default_bottom)}px)`
  } else {
    notice.style.transform = `translate(-50%,${default_bottom}px)`
  }
  notice.innerText = tips_text
  notice.classList.add(type)

  node.appendChild(notice)

  setTimeout(()=>{
    notice.remove()
  }, 3000)
}
 
let search_input = document.querySelector('.search_input')
let app = document.getElementById('app')
window.addEventListener('keydown',function(e){
  if(e.key == 'Enter'){
    if(!search_input.value){
      createNotice(app,'请输入用户名','error')
    }

    getUser(search_input.value)
  }
})

async function getUser(keyword){
  try{
    let {data} = await axios.get(keyword)
    console.log(data,"数据");
    createCard(data)
    getTag(keyword)
    search_input.value = ''
  }catch(err){
    if(err.response.status == 404){
      createNotice(app, '没有查询到相关用户', 'error')
    }
  }
}


function createCard(user){
  let main = document.querySelector('.main')

  let card = `
  <div class="card">
    <div class='avatar'>
      <img src="${user.avatar_url}" title="${user.name}"/>
    </div>
    <div class="info">
        <div class="nickname">${user.name}</div>
        <div class="describe">${user.bio ? user.bio : '该用户很懒,还没有简介'}</div>
        <div class="focus_count">
          <div class="count">${user.followers} <strong>Followers</strong></div>
          <div class="count">${user.following} <strong>Following</strong></div>
          <div class="count">${user.public_repos} <strong>Repos</strong></div>
        </div>
        <div class="tag"></div>
    </div>
  </div>
  `

  main.innerHTML = card
  console.log(main,"看看");
}


async function getTag(keyword){
  try{
    let {data} = await axios.get(`${keyword}/repos?sort=created`)
    console.log(data);
    createTag(data)
  }catch(err){
    console.log(err,"获取标签失败");
  }
}


function createTag(list){
  let tag_list = document.querySelector('.tag')
  list.forEach(item => {
    let tag = document.createElement('a')
    tag.classList.add('tag_item')
    tag.target = '_blank'
    tag.innerText = item.name
    tag.href = item.html_url
    tag_list.appendChild(tag)
  })
}